<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * 表单验证器，异常处理器
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use App\Utils\AppResult;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ValidationExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->stopPropagation();
        // 统一返回格式
        return AppResult::response203($throwable->validator->errors()->first());
//        /** @var \Hyperf\Validation\ValidationException $throwable */
//        $body = json_encode([
//            'code'    => 203,
//            'message' => $throwable->validator->errors()->first(),
//            'result'  => null
//        ], JSON_UNESCAPED_UNICODE);
//        if (!$response->hasHeader('content-type')) {
//            $response = $response->withAddedHeader('content-type', 'application/json; charset=utf-8');
//        }
//        return $response->withStatus(200)->withBody(new SwooleStream($body));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}
